package com.xtool.livewallpaper.util

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import android.provider.Settings
import com.ricky.enavigation.ENavigation
import com.xtool.livewallpaper.R
import com.xtool.livewallpaper.base.ActivityStackManager
import com.xtool.livewallpaper.base.AlertDialog
import com.xtool.livewallpaper.base.BaseActivity
import com.xtool.livewallpaper.base.getColorCompat
import com.xtool.livewallpaper.base.getString


/**
 * @ClassName: SystemRouterUtil
 * @Description:
 * @Author: Ricky Hal
 * @Date: 2021/4/16 20:13
 */
object SystemRouterUtil {

    @SuppressLint("IntentReset")
    fun chooseVideo(activity: BaseActivity, onSuccess: (Uri) -> Unit) {

        val intent = Intent(
            Intent.ACTION_PICK,
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        )
        intent.type = "video/*"
        ENavigation.with(activity)
            .setAction(Intent.ACTION_PICK)
            .setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
            .setType("video/*")
            .onResult { _, _, data ->
                data?.data?.let { uri ->
                    onSuccess(uri)
                } ?: ToastUtil.show(R.string.choose_video_failed)
            }.navigate()
    }

    fun goHome() {
        ActivityStackManager.currentActivity?.run {
            val homeIntent = Intent(Intent.ACTION_MAIN)
            homeIntent.addCategory(Intent.CATEGORY_HOME)
            homeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            startActivity(homeIntent)
        }
    }

    fun runWithAlertPermission(context: Context, title: String, block: () -> Unit) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (Settings.canDrawOverlays(context)) {
                block()
            } else {
                val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
                val dialog = AlertDialog.AlertBuilder(context)
                    .setContent(title)
                    .setRightText(getString(R.string.to_open))
                    .setLeftText(getString(R.string.cancel))
                    .setLeftTextColor(getColorCompat(R.color.gray, context))
                    .setRightTextColor(getColorCompat(R.color.on_surface, context))
                    .setRightAction {
                        context.startActivity(intent)
                        it.dismiss()
                    }
                    .setLeftAction {
                        it.dismiss()
                    }.build()
                dialog.show()
            }
        } else {
            block()
        }
    }
}